package net.toocruel.iqismart.entity.core;

import io.jsonwebtoken.lang.Collections;
import net.toocruel.iqismart.entity.base.BaseEntity;
import net.toocruel.iqismart.entity.common.Category;
import net.toocruel.iqismart.entity.common.Tag;
import net.toocruel.iqismart.entity.rbac.User;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.persistence.*;
import java.util.Set;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/8 上午11:35
 */
@Entity
public class Article extends BaseEntity {
    private static final long serialVersionUID = -1274973696950950174L;
    @ManyToOne(cascade = CascadeType.DETACH,fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "userId")
    private User user;
    private String logo;
    @ManyToOne
    @JoinColumn(name = "categoryId")
    private Category category;
    @Transient
    private Long categoryId;
    private String title;
    @Column(length = 500)
    private String summary;
    @Column(length = 10000)
    private String content;

    @ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinTable(name = "article_related",joinColumns = @JoinColumn(name = "articleId"),inverseJoinColumns = @JoinColumn(name = "relatedQuestionsId"))
    private Set<Question> relatedQuestions;

    @ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinTable(name = "article_related",joinColumns = @JoinColumn(name = "articleId"),inverseJoinColumns = @JoinColumn(name = "relatedArticlesId"))
    private Set<Article> relatedArticles;

    @ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinTable(name = "article_tag",joinColumns = @JoinColumn(name = "articleId"),inverseJoinColumns = @JoinColumn(name = "tagId"))
    private Set<Tag> tags;
    @Transient
    private String tagNames;

    @OneToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY,mappedBy = "article")
    private Set<Comment> comments;

    //一对多  比如 一个收藏记录 只能对应一个文章
    @OneToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY,mappedBy = "article")
    private Set<Collection> collections;

    @OneToMany(cascade = CascadeType.DETACH,fetch = FetchType.LAZY,mappedBy = "article")
    private Set<Support> supports;

    @Transient
    private Boolean support = false;

    @Transient
    private Boolean collected = false;
    private Long syncedAt;
    private int commentNum;
    @Transient
    private int supportNum;

    private Integer best ;
    private Integer recommend ;

    private int views;
    private int status;
    private byte device;
    private Long lastAnswer;

    public Long getLastAnswer() {
        return lastAnswer;
    }

    public void setLastAnswer(Long lastAnswer) {
        this.lastAnswer = lastAnswer;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getLogo() {
        return logo;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Set<Question> getRelatedQuestions() {
        return relatedQuestions;
    }

    public void setRelatedQuestions(Set<Question> relatedQuestions) {
        this.relatedQuestions = relatedQuestions;
    }

    public Set<Tag> getTags() {
        return tags;
    }

    public void setTags(Set<Tag> tags) {
        this.tags = tags;
    }

    public Set<Comment> getComments() {
        return comments;
    }

    public void setComments(Set<Comment> comments) {
        this.comments = comments;
    }

    public Set<Collection> getCollections() {
        return collections;
    }

    public void setCollections(Set<Collection> collections) {
        this.collections = collections;
    }

    public Set<Support> getSupports() {
        return supports;
    }

    public void setSupports(Set<Support> supports) {
        this.supports = supports;
    }

    public Boolean getSupport() {
        User currentUser = null;
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(principal instanceof User){
                currentUser = (User) principal;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollectionUtils.isNotEmpty(supports) && currentUser!=null){
            User finalCurrentUser = currentUser;
            supports.forEach(sp -> {
                if(sp.getUser().getId().equals(finalCurrentUser.getId())){
                    support = true;
                }
            });
        }
        return support;
    }

    public void setSupport(Boolean support) {
        this.support = support;
    }

    public Boolean getCollected() {
        User currentUser = null;
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(principal instanceof User){
                currentUser = (User) principal;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollectionUtils.isNotEmpty(collections) && currentUser!=null){
            User finalCurrentUser = currentUser;
            collections.forEach(sp -> {
                if(sp.getUser().getId().equals(finalCurrentUser.getId())){
                    collected = true;
                }
            });
        }
        return collected;
    }

    public void setCollected(Boolean collected) {
        this.collected = collected;
    }

    public int getViews() {
        return views;
    }

    public void setViews(int views) {
        this.views = views;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public byte getDevice() {
        return device;
    }

    public void setDevice(byte device) {
        this.device = device;
    }

    public String getTagNames() {
        StringBuffer sb = new StringBuffer();
        if(!Collections.isEmpty(tags)){
            tags.forEach(tag -> sb.append(tag.getName()).append(","));
            sb.deleteCharAt(sb.length()-1);
            return sb.toString();
        }
        return tagNames;
    }

    public void setTagNames(String tagNames) {
        this.tagNames = tagNames;
    }

    public Long getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }

    public Long getSyncedAt() {
        return syncedAt;
    }

    public void setSyncedAt(Long syncedAt) {
        this.syncedAt = syncedAt;
    }

    public int getCommentNum() {
        return commentNum;
    }

    public void setCommentNum(int commentNum) {
        this.commentNum = commentNum;
    }

    public Set<Article> getRelatedArticles() {
        return relatedArticles;
    }

    public void setRelatedArticles(Set<Article> relatedArticles) {
        this.relatedArticles = relatedArticles;
    }

    public Integer getBest() {
        return best;
    }

    public void setBest(Integer best) {
        this.best = best;
    }

    public Integer getRecommend() {
        return recommend;
    }

    public void setRecommend(Integer recommend) {
        this.recommend = recommend;
    }

    public int getSupportNum() {
        if(CollectionUtils.isNotEmpty(supports)){
            supportNum = supports.size();
        }
        return supportNum;
    }

    public void setSupportNum(int supportNum) {
        this.supportNum = supportNum;
    }
}
